/* eslint-disable */
Date.prototype.format = function (format) {
  var o = {
    "M+": this.getMonth() + 1, //month
    "d+": this.getDate(),    //day
    "h+": this.getHours(),   //hour
    "m+": this.getMinutes(), //minute
    "s+": this.getSeconds(), //second
    "q+": Math.floor((this.getMonth() + 3) / 3),  //quarter
    "S": this.getMilliseconds() //millisecond
  }
  if (/(y+)/.test(format)) format = format.replace(RegExp.$1,
    (this.getFullYear() + "").substr(4 - RegExp.$1.length))
  for (var k in o) if (new RegExp("(" + k + ")").test(format))
    format = format.replace(RegExp.$1,
      RegExp.$1.length == 1 ? o[k] :
        ("00" + o[k]).substr(("" + o[k]).length))
  return format
}

/**
 * f
*/
export class API {
  constructor () {
    this.KEY = 'DATAS_ONE'
    this.TOKEN = ''
    this.COOKIE = ''
    this.API = 'http://m.wufazhuce.com/one/ajaxlist/'
  }

  /**
   * 获取数据接口token
  */
  getToken () {
    const self = this
    return new Promise((resolve, reject) => {
      if (self.TOKEN) return resolve(self.TOKEN)
      wx.request({
        url: 'http://m.wufazhuce.com/one',
        responseType: 'text',
        success (res) {
          let {data} = res
          // cookie
          self.COOKIE = res.header['Set-Cookie']
          // 解析token

          let token = data.split("One.token = '")[1].split("'")[0]
          if (token.length === 40) {
            self.TOKEN = token
            return resolve(token)
          }
          reject('获取token失败')
        },
        fail: reject
      })
    })
  }

  /**
   * 获取数据接口
  */
  getData (page) {
    const self = this
    return new Promise((resolve, reject) => {
      // 获取缓存
      let HAS_CACHE = self.getCache()
      if (HAS_CACHE !== false) return resolve(HAS_CACHE)

      self.getToken()
        .then(token => {
          wx.request({
            url: self.API + page +'?_token=' + token,
            dataType: 'json',
            header: {
              'Cookie': self.COOKIE
            },
            success (res) {
              let {data} = res.data
              if (Array.isArray(data)) {
                // 存储缓存
                wx.setStorageSync(self.KEY, data)
                return resolve(data)
              }
            },
            fail: reject('获取数据失败')
          })
        })
        .catch(reject)
    })
  }

  /**
   * 获取本地缓存
  */
  getCache () {
    let datas = wx.getStorageSync(this.KEY)
    if (!datas) return false
    // 判断时间
    let data = datas[0]
    if (data.date === new Date().format('yyyy / MM / dd')) return datas
    return false
  }

  /**
   * 根据ID获取单条数据
   * 如果不存在，重新获取
  */
  getDataById (id) {
    const self = this
    return new Promise((resolve, reject) => {
      self.getData()
        .then(datas => {
          let data = {}
          datas.map(d => {
            if (parseInt(d.id) === parseInt(id)) data = d
          })
          return resolve(data)
        })
    })
  }
}
